package com.liaoyifan.core.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.liaoyifan.core.constant.Constants;
import com.liaoyifan.core.constant.Properties;
import com.liaoyifan.core.converter.NacosConverter;
import com.liaoyifan.core.properties.NacosProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

@SuppressWarnings("unused")
@Log4j2
@Configuration
@EnableConfigurationProperties(NacosProperties.class)
@ConditionalOnProperty(value = Properties.NACOS_ENABLE, havingValue = Constants.TRUE)
public class NacosConfiguration {

    @Autowired private Environment environment;
    @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties;
    @Autowired private NacosServiceManager nacosServiceManager;
    @Autowired private NacosProperties nacosProperties;

    @Bean
    @Primary
    public NacosServiceRegistry nacosServiceRegistry() throws Exception {
        NacosConverter.INSTANCE.toConfig(nacosProperties, nacosDiscoveryProperties);
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length > 0) {
            String active = activeProfiles[0];
            String namespace = nacosDiscoveryProperties.getNamespace();
            if (namespace == null || namespace.isBlank()) {
                nacosDiscoveryProperties.setNamespace(active);
                log.info("Nacos namespace not configured, using first active: {}", active);
            }
            nacosDiscoveryProperties.getMetadata().put("env", active);
        }
        nacosDiscoveryProperties.init();
        return new NacosServiceRegistry(nacosServiceManager, nacosDiscoveryProperties);
    }
}
